package sufutian.com.frameworkdemo.network.netwrok2;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import okhttp3.RequestBody;
import sufutian.com.frameworkdemo.network.IJson;
import sufutian.com.frameworkdemo.network.Json;
import sufutian.com.frameworkdemo.network.OkHttpEngine;

/**
 * Created by sufutian on 2017/6/6.
 */

public abstract class BaseNetBuiness implements IDataSource.IDataSourceListener{

    private final int FAIL=0,SUCCESS=1,LOADING=2;

    protected IBusinessListener<?> buinessListener;

    /**
     * 请求标识  get loadmore
     */
    private Object tag;
    /**
     * 回调业务结果的handler
     */
    final protected Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback(){

        @Override
        public boolean handleMessage(Message message) {
            if (buinessListener == null) {
                return true;
            }
            try {
                switch (message.what) {
                    case SUCCESS:
//                        if (message.obj instanceof IBaseBusinessResult)
//                            ((IBusinessListener<IBaseBusinessResult>) listener).onLoadComplete((IBaseBusinessResult) message.obj, getTag());
//                        else
//                            ((IBusinessListener<IJson>) listener).onLoadComplete((IJson) message.obj, getTag());
                        break;
                    case FAIL:
                        Object[] objs = (Object[]) message.obj;
                        DataSourceErrorType type = (DataSourceErrorType) objs[0];
                        String error = (String) objs[1];
                        String json = (String) objs[2];
                        buinessListener.onLoadFailed(new DataSourceError(type, error, json), getTag());
                        break;
                    case LOADING:
                        buinessListener.onLoading(getTag());
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
    });


    /**
     * 初始化请求业务的 标识 回调
     * @param tag
     * @param buinessListener
     */
    protected void initBusiness(Object tag, IBusinessListener<?> buinessListener) {
        cancle();
        setTag(tag);
        this.buinessListener = buinessListener;
    }

    protected void initBusiness(Object tag, IBusinessListener<?> buinessListener,boolean cancle){
        if(cancle){
            cancle();
        }
        setTag(tag);
        this.buinessListener = buinessListener;
    }

    /**
     * 初始化 业务请求的 url 和 参数
     * @param url
     * @param json
     */
    protected void initHttp(String url, Json json){
        OkHttpEngine.getOkHttp().setDataSourceListener(this);
        OkHttpEngine.getOkHttp().seturl(url);
        OkHttpEngine.getOkHttp().setJson(json);
    }

    /**
     * get 请求
     * @param url
     * @param json
     */
    protected void requestGet(String url, Json json){
        initHttp(url,json);
        OkHttpEngine.getOkHttp().get();
    }

    /**
     *  post 请求
     * @param server
     * @param json
     * @param body
     */
    protected void requestpost(String server, Json json, RequestBody body) {
        initHttp(server, json);
        OkHttpEngine.getOkHttp().setBody(body);
        OkHttpEngine.getOkHttp().post();
    }





    @Override /**IDataSourceListener**/
    public void onLoading() {
        Message message = Message.obtain();
        message.what = LOADING;
        handler.sendMessage(message);
    }

    @Override /**IDataSourceListener**/
    public void onDataComplete(String data) {
        try {
            Log.i("BaseNetBuiness==", "dataComplete->" + data);
            Json json = new Json(data);
            int result = json.getInt("result");
            if (result == 0) {  //??????????????不同服务器处理方式不同
                Log.i("BaseNetBuiness==", "业务服务器返回的失败");
                onDataFail(DataSourceErrorType.business_error, json.getString("text"), data.toString());
                return;
            }
            onLoadComplete(json); //成功
        } catch (Exception e) {
            onDataFail(DataSourceErrorType.data_error, "解析返回接口出错", data.toString());
            Log.i("BaseNetBuiness==", "解析返回接口出错");
        }
    }

    /**
     * 子类继承 去解析结果
     * @param json
     */
    protected abstract void onLoadComplete(IJson json);

    /**
     *  解析完结果 post给handler
     * @param result
     */
    protected void post(final Object result) {
        Message message = Message.obtain();
        message.obj = result;
        message.what = SUCCESS;
        handler.sendMessage(message);
    }


    @Override  /**IDataSourceListener**/
    public void onDataFail(DataSourceErrorType type, String error, String json) {
        Message message = Message.obtain();
        message.obj = (new Object[]{type, error, json});
        message.what = FAIL;
        handler.sendMessage(message);
    }

    /**
     * 取消网络请求
     */
    public void cancle(){
        OkHttpEngine.getOkHttp().cancel();
    }




    public Object getTag() {
        return tag;
    }

    public void setTag(Object tag) {
        this.tag = tag;
    }
}
